<template>
  <div v-loading="loading">
    <div v-if="subPageFlag==false" class="fl-container">
      <!-- 查询与新增 -->
      <el-form ref="queryform" :model="queryform" :inline="true">
        <el-form-item>
          <el-input v-model="queryform.system" placeholder="系统名称" class="wl-input" @input="handleQuery()" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryform.jobType" placeholder="任务周期" clearable @change="handleQuery()">
            <el-option label="日" value="D"></el-option>
            <el-option label="周" value="W"></el-option>
            <el-option label="月" value="M"></el-option>
            <el-option label="年" value="Q"></el-option>
            <el-option label="季度" value="Y"></el-option>
            <el-option label="分钟" value="I"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryform.enable" placeholder="开启状态" clearable @change="handleQuery()">
            <el-option label="停止" value="0" />
            <el-option label="启动" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="queryform.jobName" placeholder="任务名称(模糊查询)" class="wl-input" @input="handleQuery()">
            <el-button slot="append" type="primary" icon="el-icon-search" class="wl-search" @click="handleQuery()" />
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-plus" @click="addOrEdit('add', null)">新建任务<i class=" el-icon--right" /></el-button>
        </el-form-item>
      </el-form>
      <el-form ref="queryform2" :model="queryform" :inline="true">
        <el-form-item>
          <el-radio-group v-model="queryform.status" class="wl-radio-group" size="small" @change="handleQuery()">
            <el-radio-button label="">所有</el-radio-button>
            <el-radio-button label="Running">执行中</el-radio-button>
            <el-radio-button label="Pending">挂起</el-radio-button>
            <el-radio-button label="Done">成功</el-radio-button>
            <el-radio-button label="Failed">失败</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <!-- 列表 -->
      <el-table :data="list" :header-cell-style="{background:'#f4f4f5','text-align':'center'}" class="wl-table" border>
        <el-table-column type="index" label="ID" min-width="60" width="80" align="center" fixed></el-table-column>
       
        <el-table-column prop="etlSystem" :show-overflow-tooltip="true" label="ETL系统" min-width="90" width="110" align="center" fixed />
        <el-table-column prop="etlJob" :show-overflow-tooltip="true" label="ETL任务" min-width="90" width="110" align="center" fixed />
        <el-table-column prop="lastTxdate" :show-overflow-tooltip="true" label="跑批时间" min-width="100" width="135" align="center" fixed>
          <template slot-scope="scope">
            <span>{{ formatDateTime(scope.row.lastTxdate) }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="enable" :show-overflow-tooltip="true" label="开启" width="65" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.enable" :active-value="1" :inactive-value="0" active-color="#13ce66" @change="changeenable($event, scope.row)" />
          </template>
        </el-table-column> -->
        <el-table-column prop="timetrigger" label="是否时间触发" min-width="90" width="100" align="center">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.timetrigger==='Y'"  size="mini">{{ scope.row.timetrigger ==='Y'?'是':'否' }}</el-tag>
            <el-tag v-else type="info" size="mini">{{ scope.row.timetrigger ==='Y'?'是':'否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="jobtype" label="运行周期" min-width="90" width="100" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.jobtype==='Failed'" type="danger" size="mini">{{ getTypeDesc(scope.row.jobtype) }}</el-tag>
            <el-tag v-else-if="scope.row.jobtype==='Pending'" type="warning" size="mini">{{ getTypeDesc(scope.row.jobtype) }}</el-tag>
            <el-tag v-else-if="scope.row.jobtype==='Running'" type="success" size="mini">{{ getTypeDesc(scope.row.jobtype) }}</el-tag>
            <el-tag v-else-if="scope.row.jobtype==='Done'" type="success" size="mini">{{ getTypeDesc(scope.row.jobtype) }}</el-tag>
            <el-tag v-else type="info" size="mini">{{ getTypeDesc(scope.row.jobtype) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastJobstatus" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.lastJobstatus==='Failed'" type="danger" size="mini">{{ getStatusDesc(scope.row.lastJobstatus) }}</el-tag>
            <el-tag v-else-if="scope.row.lastJobstatus==='Pending'" type="warning" size="mini">{{ getStatusDesc(scope.row.lastJobstatus) }}</el-tag>
            <el-tag v-else-if="scope.row.lastJobstatus==='Running'" type="success" size="mini">{{ getStatusDesc(scope.row.lastJobstatus) }}</el-tag>
            <el-tag v-else-if="scope.row.lastJobstatus==='Done'" type="success" size="mini">{{ getStatusDesc(scope.row.lastJobstatus) }}</el-tag>
            <el-tag v-else type="info" size="mini">{{ getStatusDesc(scope.row.lastJobstatus) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastStarttime" :show-overflow-tooltip="true" label="开始时间" min-width="100" width="135" align="center" fixed>
          <template slot-scope="scope">
            <span>{{ formatDateTime(scope.row.lastStarttime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="lastEndtime" :show-overflow-tooltip="true" label="结束时间" min-width="100" width="135" align="center" fixed>
          <template slot-scope="scope">
            <span>{{ formatDateTime(scope.row.lastEndtime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createUser" :show-overflow-tooltip="true" label="提交人员" min-width="70" width="100" align="center" />
        <el-table-column prop="creationDate" :show-overflow-tooltip="true" label="创建时间" min-width="100" width="135" align="center" >
          <template slot-scope="scope">
            <span>{{ formatDateTime(scope.row.creationDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="operate" label="操作" width="210" align="center" fixed="right">
          <template slot-scope="scope">
            <el-link v-if="scope.row.enable==='0'" type="success" icon="el-icon-video-play" @click.native="beforeRun(scope.row)">启动</el-link>
            <el-link v-if="scope.row.enable==='1'" type="warning" icon="el-icon-switch-button" @click.native="stopTask(scope.row)">停止</el-link>
            <el-link type="info" icon="el-icon-view" @click.native="addOrEdit('view', scope.row)">查看</el-link>
            <el-link v-if="scope.row.enable==='0'" type="primary" icon="el-icon-edit-outline" @click.native="addOrEdit('edit', scope.row)">修改</el-link>
            <el-link v-if="scope.row.enable==='0'" type="danger" icon="el-icon-delete" @click.native="deleteEtlJob(scope.row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="pageshow"
        class="wl-pagination"
        background
        layout="total, sizes, prev, pager, next"
        :current-page="currentPage"
        :page-sizes="[10, 15, 20, 50, 100, 150, 200]"
        :page-size="pageSize"
        :total="count"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <el-dialog title="请选择执行时间" :visible.sync="dialogVisible" width="20%">
      <el-form ref="form" :model="form" label-width="60px">
        <el-form-item label="时间">
          <!-- <el-input v-model="form.lastTxdate"></el-input> -->
          <el-date-picker v-model="lastTxdate" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="startTask">确定</el-button>
      </el-form>
      </el-dialog>

      <el-dialog :title="dialogT" :visible.sync="openDialog">
      <el-form
        label-position="right"
        label-width="80px"
        :model="saveform"
        ref="saveform"
      >
        <el-row>
          <el-col :span="11">
            <el-form-item label="系统名称:">
              <el-input
                v-model="saveform.etlSystem"
                placeholder="请输入系统名称"
                :disabled="enable"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="2">
            <span style="width:1%"></span>
          </el-col>

          <el-col :span="11">
            <el-form-item label="作业名称:">
              <el-input
                v-model="saveform.etlJob"
                placeholder="请输入作业名称"
                :disabled="enable"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
      <el-col :span="11">
        <el-form-item label="系统描述:">
          <el-input v-model="saveform.description" placeholder="请输入系统描述" :disabled="enable"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="2">
        <span style="width:1%"></span>
      </el-col>

      <el-col :span="11">
        <el-form-item label="优先级:">
          <el-select v-model="saveform.jobPriority" placeholder="请选择优先级" :disabled="enable"> 
            <el-option label="普通" value="1"></el-option>
            <el-option label="高" value="2"></el-option>
            <el-option label="中" value="3"></el-option>
            <el-option label="低" value="4"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="22">
        <el-form-item label="是否以作业名命名">
          <el-radio-group v-model="saveform.isNameByJob" :disabled="enable">
            <el-radio label="Y">是</el-radio>
            <el-radio label="N">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row v-if="saveform.isNameByJob=='Y'">
      <el-col :span="11">
        <el-form-item label="执行命令:">
          <el-input v-model="saveform.cmdScript" placeholder="请输入执行命令" :disabled="enable"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="2">
        <span style="width:1%"></span>
      </el-col>

      <el-col :span="11">
        <el-form-item label="脚本类型:">
          <el-input v-model="saveform.cmdType" placeholder="请输入脚本类型:" :disabled="enable"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row v-if="saveform.isNameByJob=='Y'">
      <el-col :span="11">
        <el-form-item label="脚本存放路径:">
          <el-input type="textarea" v-model="saveform.jobCmd" :disabled="enable"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="2">
        <span style="width:1%"></span>
      </el-col>

      <el-col :span="11">
        <el-form-item label="脚本参数">
          <el-input v-model="saveform.params" :disabled="enable"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="22" v-if="saveform.isNameByJob=='N'">
        <el-form-item label="执行脚本">
          <el-input type="textarea" v-model="saveform.runningScript" :disabled="enable"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row style="height: 29px;color: red;margin-left: 8%;" v-if="saveform.isNameByJob=='Y'">
      <el-col :span="2">
        <span style="width:1%"></span>
      </el-col>
      <el-col :span="14">注:执行脚本生成规则==》执行命令+空格+ 脚本存放位置+作业名小写+.作业类型+ 空格+参数</el-col>
    </el-row>

    <el-row>
      <el-col :span="11">
        <el-form-item label="执行周期:">
          <el-select v-model="saveform.jobType" placeholder="请选择作业跑批周期" :disabled="enable">
            <el-option label="日" value="D"></el-option>
            <el-option label="周" value="W"></el-option>
            <el-option label="月" value="M"></el-option>
            <el-option label="年" value="Q"></el-option>
            <el-option label="季度" value="Y"></el-option>
            <el-option label="分钟" value="I"></el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="2">
        <span style="width:1%"></span>
      </el-col>

      <el-col :span="11">
        <el-form-item label="组别:">
          <el-select v-model="saveform.groupId" placeholder="请选择ETL服务器组号" :disabled="enable">
            <el-option label="1" value="1"></el-option>
            <el-option label="2" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="22">
        <el-form-item label="触发类型">
          <el-radio-group v-model="saveform.timetrigger" @change="findSystems()" :disabled="enable">
            <el-radio label="Y">时间触发</el-radio>
            <el-radio label="N">依赖触发</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row v-if="saveform.timetrigger == 'Y' && saveform.jobType == 'W'">
      <el-col :span="22">
        <el-form-item label="执行星期">
          <el-input v-model="saveform.startwday" placeholder="请输入星期或选择星期" :disabled="enable"></el-input>
        </el-form-item>
      </el-col>
      <el-col>
        <el-form-item>
          <el-checkbox-group v-model="wday" @change="getcheck(wday, 'W')" :disabled="enable">
            <el-checkbox
              v-for="(item, index) in weeks"
              :key="index"
              :label="item"
              :checked="item.ischeck"
            >{{ item.label }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-col>
    </el-row>

    <!--  -->
    <el-row
      v-if="
        saveform.timetrigger == 'Y' &&
          (saveform.jobType == 'M' || saveform.jobType == 'Y' || saveform.jobType == 'Q')
      "
    >
      <el-col :span="22">
        <el-form-item label="执行日期">
          <el-input v-model="saveform.startmday" placeholder="请选择或输入执行日期" :disabled="enable"></el-input>
        </el-form-item>
      </el-col>
      <el-col>
        <el-form-item>
          <el-checkbox-group v-model="mday" @change="getcheck(mday, 'D')">
            <el-checkbox v-for="index in 31" :key="index" :label="index" :value="index" :disabled="enable"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row
      v-if="
        saveform.timetrigger == 'Y' && (saveform.jobType == 'Y' || saveform.jobType == 'Q')
      "
    >
      <el-col :span="22">
        <el-form-item label="执行月份">
          <el-input v-model="saveform.startmon" placeholder="请选择或输入执行月份" :disabled="enable"></el-input>
        </el-form-item>
      </el-col>
      <el-col>
        <el-form-item>
          <el-checkbox-group v-model="mons" @change="getcheck(mons, 'M')">
            <el-checkbox v-for="index in 12" :key="index" :label="index" :value="index" name="type" :disabled="enable"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row v-if="saveform.timetrigger == 'Y'">
      <el-col :span="11" v-if="saveform.jobType !== 'I'">
        <el-form-item label="开始小时:">
          <el-select v-model="saveform.starthour" placeholder="请选择开始小时" :disabled="enable">
            <el-option v-for="index in 24" :key="index-1" :label="index-1" :value="index-1" ></el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="2">
        <span style="width:1%"></span>
      </el-col>

      <el-col :span="11">
        <el-form-item label="开始分钟:">
          <el-select v-model="saveform.startmin" placeholder="请选择开始分钟" :disabled="enable">
            <el-option v-for="index in 60" :key="index-1" :label="index-1" :value="index-1" ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row v-if="saveform.timetrigger != 'Y'">
      <el-col :span="11">
        <el-form-item label="选择系统:">
          <el-select v-model="saveform.dependenceSystem" placeholder="请选择系统" @change="findJob(saveform.dependenceSystem)" :disabled="enable">
            <el-option v-for="index in systems" :key="index" :label="index" :value="index" ></el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="2">
        <span style="width:1%"></span>
      </el-col>

      <el-col :span="11">
        <el-form-item label="依赖作业:">
          <el-select v-model="saveform.dependenceJob" placeholder="请选择依赖作业" :disabled="enable">
            <el-option v-for="i in jobs" :key="i" :label="i" :value="i"></el-option>
          </el-select>
          <el-button @click.native="addDependenceJob" v-if="!enable">添加</el-button>
          <el-input v-model="saveform.dependenceJobs" style="width: 70%;"></el-input>
          <el-button @click.native="clearJob" v-if="!enable">清空</el-button>
        </el-form-item>
        <el-form-item label></el-form-item>
      </el-col>
    </el-row>

      <el-form-item style="height:100px" v-if="!enable">
        <el-button type="primary" @click.native="save('n')" >创建</el-button>
        <el-button type="primary" @click="closeEtlDialog">取消</el-button>
      </el-form-item>
      </el-form>
    </el-dialog>
    </div>
    <!-- 子菜单路由 -->
    <router-view />
  </div>
</template>

<script>
import { etlJobList,startEtlJob,stopEtlJob,addJob,deleteEtlJob,findSystems,findJobBySystemName,findJobCommandById,
         findTimeTriggerById,findDependenceJob } from '@/api/etl'
import { getToken } from '@/utils/auth'

export default {
  name: 'EtlTaskManage',
  components: {
  },
  data() {
    return {
      loading: false,
      subPageFlag: false, // 当打开子菜单时，当前页内屏蔽
      queryform: {
        system: '',
        jobName: '',
        userName: '',
        jobType: '',
        enable: '',
        status: ''
      },
      list: [],
      count: 0,
      pageSize: 15,
      currentPage: 1,
      pageshow: true,
      user:{},
      dialogVisible:false,
      closeDialog:false,
      lastTxdate:null,
      form:{},
      saveform: {
        etlSystem: "", //系统
        etlJob: "", //作业名称
        description: "",
        jobPriority: null, //优先级
        cmdScript: "", //执行命令
        cmdType: "", //脚本类型
        params: "", //脚本参数
        jobCmd: "", //执行脚本
        runningScript: "", //执行脚本
        isNameByJob: "Y",
        jobType: "", //执行周期
        timetrigger: "Y", //是否时间触发
        startwday: "", //执行星期
        startmday: "", //执行日期
        startmon: "", //执行月份
        starthour: null, //执行时间开始小时
        startmin: null, //执行时间开始分钟
        groupId: "",
        userId: "",
        dependenceSystem: "",
        dependenceJob: "",
        dependenceJobs: ""
      },
      //控制弹窗的打开与关闭
      openDialog: false,
      dialogT: "新增",
      enable: false,
      wday: [],
      mday: [],
      mons: [],
      weeks: [
        {
          label: "星期一",
          value: "1",
          ischeck: false,
        },
        {
          label: "星期二",
          value: "2",
          ischeck: false,
        },
        {
          label: "星期三",
          value: "3",
          ischeck: false,
        },
        {
          label: "星期四",
          value: "4",
          ischeck: false,
        },
        {
          label: "星期五",
          value: "5",
          ischeck: false,
        },
        {
          label: "星期六",
          value: "6",
          ischeck: false,
        },
        {
          label: "星期日",
          value: "7",
          ischeck: false,
        },
      ],
      execCommand: "",
      systems: [],
      jobs: [],
      timer:null
    }
  },
  mounted() {
    if (this.$route.name === 'EtlTaskManage') {
      this.subPageFlag = false
      const params = this.$route.params
      if (params && params.currentPage) {
        this.queryform.system = params.system
        this.queryform.jobName = params.jobName
        this.queryform.userName = params.userName
        this.queryform.jobType = params.jobType
        this.queryform.enable = params.open
        this.queryform.status = params.status
        if (params.currentPage) { // 恢复分页状态
          this.count = params.count
          this.currentPage = params.currentPage
          this.pageSize = params.pageSize
        }
      }
      const token = getToken()
      this.user = JSON.parse(token)
      this.setTimeToRun()
      
    } else {
      this.subPageFlag = true
    }
  },
  methods: {
    queryContent() {
      return {
        count: this.count,
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        system: this.queryform.system,
        jobName: this.queryform.jobName,
        userName: this.queryform.userName,
        jobType: this.queryform.jobType,
        open: this.queryform.enable,
        status: this.queryform.status
      }
    },
    setTimeToRun() {
      if(!this.timer)
        this.handleQuery();
      this.timer = setInterval(() => {
        this.handleQuery();
      }, 5000);

      this.$once("hook:beforeDestroy", () => {
        clearInterval(this.timer);
        this.timer = null;
      });
    },
    handleQuery() { // 查询
      this.pageshow = false
      this.getTasks()
      this.$nextTick(() => { this.pageshow = true }) // 解决界面页码不更新问题
    },
    handleSizeChange(pageSize) { // 设置分页大小事件
      this.pageSize = pageSize
      this.handleQuery()
    },
    handleCurrentChange(pageno) { // 处理分页事件
      this.currentPage = pageno
      this.handleQuery()
    },
    save: function () {
      this.$refs.saveform.validate((valid) => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.handleTime(this.saveform.jobType)
            let para = Object.assign({}, this.saveform);
            para.userId = !!this.user ? this.user.username : "";
            console.log("para", para);
            addJob(para).then((res) => {
              if (res.result) {
                this.$message({
                  message: "提交成功",
                  type: "success",
                });
                this.closeEtlDialog()
                this.handleQuery()
              } else {
                this.$message({
                  message: "系统作业已存在!",
                  type: "info",
                });
              }
            });
          });
        }
      });
    },
    // 对保存时间触发作处理
    handleTime(type){
      if(type == 'D'){
        this.saveform.startwday=''
        this.saveform.startmday=''
        this.saveform.startmon=''
      }
      if(type == 'W'){
        this.saveform.startmday=''
        this.saveform.startmon=''
      }
      if(type == 'M'){
        this.saveform.startwday=''
        this.saveform.startmon=''
      }
      if(type == 'Q'||type == 'Y'){
        this.saveform.startwday=''
      }
      if(type == 'I'){
        this.saveform.startwday=''
        this.saveform.startmday=''
        this.saveform.startmon=''
        this.saveform.starthour=''
      }
      console.log('this.saveform.......',this.saveform)
    },
    addOrEdit(type, data) {
      this.openDialog = true
      this.enable = false
      if (type == "add") {
        //新增时
        this.dialogT = "新增"
        this.cleanForm()
      } else {
        if (type == "edit") {
          this.dialogT = "编辑"
        } else {
          this.dialogT = "查看"
          this.enable = true
        }

         this.saveform.etlSystem = data.etlSystem;
         this.saveform.etlJob = data.etlJob;
         this.saveform.description = data.description;
         this.saveform.jobPriority = data.jobPriority;
         this.saveform.jobType = data.jobtype;
         this.saveform.groupId = data.groupId;
         this.saveform.timetrigger = !data.timetrigger ? "N" : "Y"
         this.getCmdData(data.etlSystem, data.etlJob);
         // 查询 命令实体数据
         this.getTimetrigger(data.etlSystem, data.etlJob);
         this.findDependenceJob(data.etlSystem + "." + data.etlJob + " dep");
         this.findSystems();
      }
    },
    getCmdData(etlSystem, etlJob) {
      findJobCommandById(etlSystem, etlJob).then((res) => {
        let result = res.result;
        if (!!result) {
          this.execCommand = result[0].execCommand;
          console.log("this.execCommand", this.execCommand);
          this.saveform.cmdScript = this.execCommand.split(" ")[0];
          this.saveform.cmdType = this.execCommand.split(".")[1].split(" ")[0];
          this.saveform.params = this.execCommand.split(".")[1].split(" ")[1]
            ? this.execCommand.split(".")[1].split(" ")[1]
            : "";
          this.saveform.jobCmd = this.execCommand.substring(
            this.execCommand.indexOf(" "),
            this.execCommand.lastIndexOf("/")
          );
          this.saveform.isNameByJob =
            this.execCommand
              .split(".")[0]
              .substring(this.execCommand.lastIndexOf("/"))
              .indexOf(this.saveform.etlJob) != -1
              ? "Y"
              : "N";
          this.saveform.runningScript = this.execCommand;
        }
      });
    },
    getTimetrigger(etlSystem, etlJob) {
      findTimeTriggerById(etlSystem, etlJob).then((res) => {
        let result = res.result[0];
        if (!!result) {
          this.saveform.starthour = result.starthour;
          this.saveform.startmin = result.startmin;
          this.saveform.startwday = result.startwday;
          this.saveform.startmday = result.startmday;
          this.saveform.startmon = result.startmon;
          if (!!this.saveform.startmday)
            this.mday = this.saveform.startmday.split(",").map(Number);

          if (!!this.saveform.startwday)
            this.wday = this.weeks.filter((item) => {
              return this.saveform.startwday.includes(item.value);
            });
          if (!!this.saveform.startmon)
            this.mons = this.saveform.startmon.split(",").map(Number);
          console.log('时间。。。',this.mday, this.wday, this.mons);

        }
      });
    },
    findDependenceJob(systemName) {
      findDependenceJob(systemName).then((res) => {
        this.saveform.dependenceJobs = res.result.toString();
        if (this.saveform.dependenceJobs.length > 0)
          this.saveform.dependenceJobs = this.saveform.dependenceJobs + ",";
      });
    },
    getcheck(value, data) {
      var childId = []; //初始化为空存用来存着选中的id
      value.forEach((item) => {
        //value是对应复选框选中的每一条数据
        //周
        if (data == "W" && childId.indexOf(item.value) == -1) {
          childId.push(item.value);
        }
      });
      if (data == "W")
        this.saveform.startwday = childId.sort(this.compare).toString();
      if (data == "D")
        this.saveform.startmday = value.sort(this.compare).toString();
      if (data == "M") this.saveform.startmon = value.sort(this.compare).toString();
      console.log('getcheck',value, data);
    },
    // 比较，用于sort数组排序
    compare(a, b) {
      return a - b;
    },
    cleanForm() {
      this.saveform = {
        etlSystem: "", //系统
        etlJob: "", //作业名称
        description: "",
        jobPriority: null, //优先级
        cmdScript: "", //执行命令
        cmdType: "", //脚本类型
        params: "", //脚本参数
        jobCmd: "", //执行脚本
        runningScript: "", //执行脚本
        isNameByJob: "Y",
        jobType: "", //执行周期
        timetrigger: "Y", //是否时间触发
        startwday: "", //执行星期
        startmday: "", //执行日期
        startmon: "", //执行月份
        starthour: null, //执行时间开始小时
        startmin: null, //执行时间开始分钟
        groupId: "",
        userId: "",
        dependenceSystem: "",
        dependenceJob: "",
        dependenceJobs: ""
      }
      this.wday= []
      this.mday= []
      this.mons= []
    },
    //查询所有的系统名称
    findSystems() {
      findSystems(this.user.username).then((res) => {
        if(res.status == true){
          this.systems = res.result;
        }
      });
    },

    findJob(systemName) {
      this.saveform.dependenceJob = "";
      if (!!systemName) {
        findJobBySystemName(systemName).then((res) => {
          if(res.status == true){
            this.jobs = res.result;
          }
          console.log("this.jobs", this.jobs)
        });
      }
    },
    addDependenceJob() {
      console.log('this.saveform.dependenceJobs',this.saveform.dependenceJobs,this.saveform)
      if (
        !!this.saveform.dependenceSystem &&
        !!this.saveform.dependenceJob &&
        this.saveform.dependenceJobs.indexOf(
          this.saveform.dependenceSystem + "|" + this.saveform.dependenceJob
        ) == -1
      ) {
        this.saveform.dependenceJobs +=
          this.saveform.dependenceSystem + "|" + this.saveform.dependenceJob + ","
      }
      //  this.form.dependenceSystem =  this.form.dependenceSystem.substr(0,this.form.dependenceSystem.length-1)
    },
    clearJob() {
      this.saveform.dependenceJobs = "";
    },
    closeEtlDialog() {
      this.openDialog = false;
      this.cleanForm()
      this.$refs["saveform"].resetFields();
    },
    getTasks() { // 查询任务列表
      this.loading = true
      this.queryform.userName = this.user.username
      etlJobList(this.currentPage, this.pageSize, this.queryform ).then(response => {
        this.loading = false
        const { status, message, result } = response
        if (status !== true) {
          this.$message({ type: 'error', message: (message || '请求数据异常！') })
          return
        }
        this.list = result.data
        console.log('dsdsdswew',this.list)
        this.count = result.total
        if (this.count > 0 && this.list.length == 0) { // 调整PageNo
          this.currentPage = Math.ceil(this.count / this.pageSize)
          this.getTasks()
        }
      }).catch(error => {
        this.loading = false
        this.$message({ type: 'error', message: '请求异常！' })
        console.log(error)
      })
    },
    beforeRun(date) {
      this.dialogVisible = true;
      this.form = date;
      this.lastTxdate = null;
      if(!!date.lastTxdate){
        this.lastTxdate = date.lastTxdate
      }
    },
    startTask() { // 启动任务
      if (!this.lastTxdate) {
        this.$message({
          message: "请选择执行时间!",
          type: "warning",
        });
      } else {
        this.$confirm("确认执行吗?", "提示", {
          type: "warning",
        }).then(() => {
          this.dialogVisible = false;
          this.loading = true
          const { etlSystem, etlJob } = this.form
          this.form.lastTxdate = this.lastTxdate
          startEtlJob(this.form).then(response => {
            this.loading = false
            const { status, message, result } = response
            if (status !== true) {
              this.$message({ type: 'error', message: (message || '请求数据异常！') })
              return
            }
            this.handleQuery()
            this.$message({ type: 'info', message: `正在启动【${etlSystem+'-'+etlJob}】，稍后请刷新！` })
            }).catch(error => {
              this.loading = false
              this.$message({ type: 'error', message: '请求异常！' })
              console.log(error)
            })}
        )}
    },
    stopTask(row) { // 停止任务
      console.log('停止任务',row)
      const { etlSystem, etlJob } = row
      this.$confirm(`确定要停止任务【${etlSystem+'-'+etlJob}】吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        stopEtlJob(row).then(response => {
          this.loading = false
          const { status, message, result } = response
          if (status !== true) {
            this.$message({ type: 'error', message: (message || '请求数据异常！') })
            return
          }
          this.handleQuery()
          this.$message({ type: 'success', message: `正在停止任务【${etlSystem+'-'+etlJob}】，稍后请刷新！` })
        }).catch(error => {
          this.loading = false
          this.$message({ type: 'error', message: '请求异常！' })
          console.log(error)
        })
      })
    },
    deleteEtlJob(row) { // 删除
      const { etlSystem, etlJob } = row
      this.$confirm(`确定要删除【${etlSystem+'-'+etlJob}】吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        deleteEtlJob(row).then(response => {
          this.loading = false
          const { status, message, result } = response
          if (status !== true) {
            this.$message({ type: 'error', message: (message || '请求数据异常！') })
            return
          }
          this.handleQuery()
          this.$message({ type: 'success', message: `删除[${etlSystem+'-'+etlJob}]成功！` })
        }).catch(error => {
          this.loading = false
          this.$message({ type: 'error', message: '请求异常！' })
          console.log(error)
        })
      })
    },
    formatDateTime(date) {
      if(!!date){
        return this.dayjs(date).format('YYYY-MM-DD HH:mm:ss')
      }else{
        return ''
      }
      
    },
    getStatusDesc(status) { // 任务状态
      switch (status) {
        case 'Failed': return '准备执行'
        case 'Pending': return '挂起中'
        case 'Running': return '执行中'
        case 'Done': return '成功'
        default: return '待启动'
      }
    },
    getTypeDesc(type){
       switch (type) {
        case 'D': return '日'
        case 'W': return '周'
        case 'M': return '月'
        case 'Q': return '季度'
        case 'Y': return '年'
        case 'I': return '分钟'
      }

    },
    getTaskTypeName(tasktype) {
      switch (tasktype) {
        case 'SQL_STREAMING': return 'SQL流任务'
        case 'SQL_BATCH': return 'SQL批任务'
        case 'JAR': return 'JAR包'
        default: return tasktype
      }
    },
    getRouteTaskName(flag, jobTypeEnum) {
      switch (flag) {
        case 'create':
          switch (jobTypeEnum) {
            case 'SQL_STREAMING': return 'CreateSqlStreamingTask'
            case 'SQL_BATCH': return 'CreateSqlBatchTask'
            case 'JAR': return 'CreateJarTask'
            default: return ''
          }
        case 'update':
          switch (jobTypeEnum) {
            case 'SQL_STREAMING': return 'UpdateSqlStreamingTask'
            case 'SQL_BATCH': return 'UpdateSqlBatchTask'
            case 'JAR': return 'UpdateJarTask'
            default: return ''
          }
        case 'view':
          switch (jobTypeEnum) {
            case 'SQL_STREAMING': return 'ViewSqlStreamingTask'
            case 'SQL_BATCH': return 'ViewSqlBatchTask'
            case 'JAR': return 'ViewJarTask'
            default: return ''
          }
        default: return ''
      }
    }
  }
}
</script>

<style scoped>
  .fl-container {
    margin: 20px;
  }
  .fl-container >>> .el-form-item {
    margin-bottom: 5px!important;
  }
  .wl-table {
    width:100%;
    margin-top: 0px;
  }
  .wl-icon {
    margin-right: 2px;
  }
  .wl-operate {
    overflow: hidden;
  }
  .wl-input {
    width: 200px;
  }
  .wl-form-input {
    width: 360px;
  }
  .wl-search {
    background: #f5f7fa;
  }
  .fl-version-text {
    /*display: inline;
    white-space: nowrap;
    text-overflow: ellipsis;*/
  }
  .fl-version-span {
    color: #337ab7;
    text-decoration: underline;
  }
  .wl-search >>> .el-button {
    background: #f00;
  }
  .wl-deploy-edit {
    padding-left: 10px;
  }
  .wl-deploy-to {
    padding-left: 8px;
  }
  .wl-delete {
    color: #f56c6c;
  }
  .wl-pagination {
    margin-top: 5px;
  }
  .wl-myicon {
    font-size: 14px;
  }
  .wl-table-icon >>> span {
    margin-left: 2px;
  }
  .wl-radio-group >>> .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    background-color: #f5f7fa;
    border-color: #DCDFE6;
    -webkit-box-shadow: -1px 0 0 0 #DCDFE6;
    box-shadow: -1px 0 0 0 #DCDFE6;
  }
  .wl-radio-group >>> .el-radio-button__inner {
    color: #606266;
  }
  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
    font-size: 12px;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  .wl-table >>> .el-link [class*=el-icon-] + span {
    margin-left: 1px;
  }
  .wl-table >>> .el-link {
    margin-right: 2px;
    margin-left: 2px;
  }
</style>
